package com.service;

import static com.def.GenericDef.ACTION_FLG_ADD;
import static com.def.GenericDef.ACTION_FLG_DELETE;
import static com.def.GenericDef.ACTION_FLG_LIST_WHOLE;
import static com.def.GenericDef.ACTION_FLG_QUERY;
import static com.def.GenericDef.ACTION_FLG_UPDATE;
import static com.def.GenericDef.BANK_OUT;
import static com.def.GenericDef.DPS_CATE_LEVEL_2;
import static com.def.GenericDef.E_ADD_EXIST;
import static com.def.GenericDef.E_DELETE_NOT_FOUND;
import static com.def.GenericDef.E_READ_NOT_FOUND;
import static com.def.GenericDef.E_RET_PRD_IN;
import static com.def.GenericDef.E_RET_WO;
import static com.def.GenericDef.E_UPDATE_NOT_FOUND;
import static com.def.GenericDef.E_XPWHSOPE_ADD_UPDATE_WOINFO_FAILED;
import static com.def.GenericDef.E_XPWHSOPE_BOX_ALREADY_RELEASED;
import static com.def.GenericDef.E_XPWHSOPE_BOX_NOT_RELEASED;
import static com.def.GenericDef.E_XPWHSOPE_INVALID_BOX_STAT;
import static com.def.GenericDef.E_XPWHSOPE_INVALID_INPUT;
import static com.def.GenericDef.E_XPWHSOPE_INVALID_USE_CHANGE_TYPE;
import static com.def.GenericDef.E_XPWHSOPE_MTRL_BOX_ALREADY_EXIST;
import static com.def.GenericDef.E_XPWHSOPE_RELEASED_BOX_BACK_ERROR;
import static com.def.GenericDef.E_XPWHSOPE_WO_PRD_MISMATCH_ERROR;
import static com.def.GenericDef.E_XPWHSOPE_MTEL_PROD_ID_MISMATCH_ERROR;
import static com.def.GenericDef.JBIC_BOX_SET_CODE;
import static com.def.GenericDef.MDL_CATES;
import static com.def.GenericDef.MDL_CATE_DM;
import static com.def.GenericDef.MDL_CATE_JB;
import static com.def.GenericDef.MDL_CATE_QG;
import static com.def.GenericDef.PROC_EMPTY;
import static com.def.GenericDef.PROC_WAIT;
import static com.def.GenericDef.PROC_WFRL;
import static com.def.GenericDef.RETURN_CODE_OK;
import static com.def.GenericDef.RETURN_CODE_SET_ERROR;
import static com.def.GenericDef.RETURN_CODE_UNKNOWN;
import static com.def.GenericDef.RETURN_MESG_OK;
import static com.def.GenericDef.TRX_IN;
import static com.def.GenericDef.TRX_OUT;
import static com.def.GenericDef.T_XPAPLYWO;
import static com.def.GenericDef.T_XPWHSOPE;
import static com.def.GenericDef._NORMAL;
import static com.def.GenericDef._SPACE0;
import static com.def.GenericDef._YES;
import static com.def.GenericDef._NO;
import static com.def.GenericDef.EVT_MTRL_IN;
import static com.def.GenericDef.EVT_MTRL_RELEASE_TO_PROD;
import static com.def.GenericDef.EVT_MTRL_IN_CANCEL;
import static com.def.GenericDef.EVT_MTRL_RELEASE_CANCEL;
import static com.def.GenericDef.E_RET_CUS_PRD_IN;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.dao.IBisDataDao;
import com.dao.IRetBoxDao;
import com.dao.IRetCusPrdInDao;
import com.dao.IRetPrdInDao;
import com.dao.IRetPrdInfoDao;
import com.dao.IRetTmCusPrdInDao;
import com.dao.IRetWODao;
import com.icim.service.ICIMBaseService;
import com.model.Ret_box;
import com.model.Ret_cus_prd_in;
import com.model.Ret_prd_in;
import com.model.Ret_prd_inId;
import com.model.Ret_tm_cus_prd_in;
import com.model.Ret_wo;
import com.rtnBean.NotFoundRtnBeen;
import com.rtnBean.SimpleRtnBeen;
import com.tx.Xpaplywo.XpaplywoI;
import com.tx.Xpaplywo.XpaplywoIA;
import com.tx.Xpaplywo.XpaplywoO;
import com.tx.Xpwhsope.XpwhsopeI;
import com.tx.Xpwhsope.XpwhsopeIA;
import com.tx.Xpwhsope.XpwhsopeO;
import com.tx.Xpwhsope.XpwhsopeOA;
import com.util.MqOpe;
import com.util.Util;

@Scope("prototype")
@Service("XpwhsopeService")
public class XpwhsopeService extends ICIMBaseService{
	private static Logger logger = Logger.getLogger(XpwhsopeService.class);
	private static String TX_NAME = T_XPWHSOPE;
	private static String USE_CHG_U = "U";
	private static String USE_CHG_R = "R";

	private XpwhsopeI inTrx;
	private XpwhsopeO outTrx;
	private MqOpe mqOpe;

	@Autowired
	private IRetPrdInDao retPrdInDao;
	@Autowired
	private IRetWODao retWODao;
	@Autowired
	private IRetBoxDao retBoxDao;
	@Autowired
	private IRetPrdInfoDao retPrdInfoDao;
	@Autowired
	private XpaplywoService xpaplywoService;
	@Autowired
	private IRetCusPrdInDao retCusPrdInDao;
	@Autowired
	private IRetTmCusPrdInDao retTmCusPrdInDao;
	
	@Autowired
	private IBisDataDao bisDataDao;
	
	private String gszMsgBuf = "";

	private Timestamp gEvtTimestamp;

	public String subMainProc(String strInMsg) {
		Session session = retPrdInfoDao.getCrSession();
		long rtnCode = _NORMAL;
		String outMsg = null;

		gszMsgBuf = "";
		gEvtTimestamp = Util.getCurrentTimestamp();
		inTrx = new XpwhsopeI();
		outTrx = new XpwhsopeO();
		outTrx.setTrx_id(TX_NAME);
		outTrx.setRtn_code(String.valueOf(RETURN_CODE_SET_ERROR));
		outTrx.setType_id(TRX_OUT);

		mqOpe = new MqOpe();

		try {
			inTrx = (XpwhsopeI) mqOpe.inStr2Obj(strInMsg, inTrx);
			logger.info("InTrx is " + strInMsg);

			rtnCode = subMainProc2(inTrx.getAction_flg().toCharArray()[0]);
			if (rtnCode != _NORMAL) {
				TransactionAspectSupport.currentTransactionStatus()
						.setRollbackOnly();
				outTrx.setRtn_code(String.valueOf(rtnCode));
				outTrx.setRtn_mesg(gszMsgBuf);
			} else {
				outTrx.setRtn_code(String.valueOf(RETURN_CODE_OK));
				outTrx.setRtn_mesg(RETURN_MESG_OK);
				session.flush();
			}
		} catch (Exception ex) {
			TransactionAspectSupport.currentTransactionStatus()
					.setRollbackOnly();
			outTrx.setRtn_mesg(ex.toString());
			outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
			logger.error(Util.stackTraceToString(ex));
		} finally {
			outMsg = mqOpe.obj2Str(outTrx);
			return outMsg;
		}
	}

	/**
	 * Real action type
	 * 
	 * @param actionType
	 * @return
	 */
	private long subMainProc2(char actionType) {
		long lRc = _NORMAL;
		switch (actionType) {
		case ACTION_FLG_ADD: {
			lRc = panelMaterialReceive();
			if (lRc != _NORMAL) {
				return lRc;
			}
			lRc = createRetBoxByMtrlBoxId();
			if (lRc != _NORMAL) {
				return lRc;
			}
			break;
		}
		case ACTION_FLG_UPDATE: {
			lRc = updatePanelMtrlRecord();
			if (lRc != _NORMAL) {
				return lRc;
			}
			lRc = createRetBoxByMtrlBoxId();
			if (lRc != _NORMAL) {
				return lRc;
			}
			break;
		}
		case ACTION_FLG_QUERY: {
			lRc = queryPanelMaterial();
			if (lRc != _NORMAL) {
				return lRc;
			}
			break;
		}
		case ACTION_FLG_DELETE: {
			lRc = deletePanelMtrlRecord();
			if (lRc != _NORMAL) {
				return lRc;
			}
			break;
		}
		case ACTION_FLG_LIST_WHOLE: {
			lRc = listPanelMaterial();
			if (lRc != _NORMAL) {
				return lRc;
			}
			break;
		}
		case 'B': {
			lRc = mtrlPanelUseChg(USE_CHG_U);
			if (lRc != _NORMAL) {
				return lRc;
			}
			break;
		}
		case 'R': {
			lRc = mtrlPanelUseChg(USE_CHG_R);
			if (lRc != _NORMAL) {
				return lRc;
			}
			break;
		}
		case 'E': {
			lRc = changeMtrlStat();
			if (lRc != _NORMAL) {
				return lRc;
			}
			break;
		}
		default: {
			gszMsgBuf = "Invalide type input: [" + actionType + "]";
			return E_XPWHSOPE_INVALID_INPUT;
		}
		}

		return lRc;
	}

	/**
	 * Add mtrl box info
	 * 
	 * @return
	 */
	private long panelMaterialReceive() {
		long lRc = _NORMAL;
		SimpleRtnBeen rtnBeen = new SimpleRtnBeen(_NORMAL);
		XpaplywoO xpaplywoO = new XpaplywoO();
		List<Ret_prd_in> ret_prd_inList = new ArrayList<Ret_prd_in>();

		if (inTrx.getBox_cnt() > 0) {
			List<XpwhsopeOA> oaList = new ArrayList<XpwhsopeOA>();
			for (XpwhsopeIA item : inTrx.getIary()) {
				Ret_prd_in ret_prd_in ;
				Ret_prd_inId ret_prd_inId = new Ret_prd_inId();

				ret_prd_inId.setMtrl_box_id(item.getBox_id());
				ret_prd_inId.setCus_id(item.getVdr_id());
				ret_prd_in = retPrdInDao.get(ret_prd_inId);
				if (null != ret_prd_in) {
					gszMsgBuf = "[" + item.getVdr_id() + "] 的箱子["
							+ item.getBox_id() + "] 已经存在且状态不为空!";
					return E_RET_PRD_IN + E_ADD_EXIST;
				}else{
					String hqlQuery = "FROM Ret_prd_in where wo_id_fk = '" + item.getWo_id() + "' and vdr_box_id = '" + item.getVdr_box_id() + "'";
					ret_prd_inList = retPrdInDao.find(hqlQuery);
					if (!ret_prd_inList.isEmpty()){
						gszMsgBuf = "[" + item.getVdr_id() + "] 的原料箱["
								+ item.getVdr_box_id() + "] 已经登记!";
						return E_RET_PRD_IN + E_ADD_EXIST;
					}
					
					/**
					 * 获取RET_WO信息和RET_CUS_PRD_IN来料信息
					 */
					//Ret_wo retWo = retWODao.get(item.getWo_id());
					Ret_wo retWo = retWODao.getWithLock(item.getWo_id(), LockMode.UPGRADE);
					Ret_cus_prd_in cusPrdIn = retCusPrdInDao.get(item.getBox_id());
					/**
					 * 检查SWH_CNT_FLG(来料标记)
					 * 需确认来料工单的来料型号和来料箱号的一致
					 * 同时updte RET_CUS_PRD_IN中的ACT_FLG(标记是否已经4100收料)为Y 
					 */
					if(retWo != null){
						if(_YES.equals(retWo.getSwh_cnt_flg())){//来料订单，来料箱必须有资料
							if(cusPrdIn != null){
								if(retWo.getMtrl_prod_id_fk().equals(cusPrdIn.getMtrl_prod_id_fk())){//来料工单的来料型号必须和来料箱号的一致
									cusPrdIn.setAct_flg(_YES);
									retCusPrdInDao.save(cusPrdIn);
								}else{
									gszMsgBuf = "内部订单[" + item.getWo_id() 
									+ "]与来料箱[" 
									+ item.getBox_id() + "]的来料型号不匹配，无法收料!";
								return E_XPWHSOPE_MTEL_PROD_ID_MISMATCH_ERROR;
								}
							}else{
								gszMsgBuf = "内部订单[" + item.getWo_id() 
									+ "]为客户来料订单，未找到来料箱[" 
									+ item.getBox_id() + "]的资料!";
								return E_RET_CUS_PRD_IN + E_READ_NOT_FOUND;
							}
						}else{
							if(cusPrdIn != null){
								gszMsgBuf = "内部订单[" + item.getWo_id() 
								+ "]为非客户来料订单，来料箱[" 
								+ item.getBox_id() + "]为客户来料箱，无法收料!";
								return E_XPWHSOPE_WO_PRD_MISMATCH_ERROR;
							}
						}
					}

					ret_prd_in = new Ret_prd_in();
					ret_prd_in.setId(ret_prd_inId);
					ret_prd_in.setVdr_box_id(item.getVdr_box_id());
					ret_prd_in.setPpbox_stat(PROC_WAIT);
					ret_prd_in.setBox_weight(Double.valueOf(item.getWeight()));
					ret_prd_in.setMtrl_prod_id_fk(retWo.getMtrl_prod_id_fk());
					ret_prd_in.setStb_shop(item.getDest_shop());
					ret_prd_in.setWo_id_fk(item.getWo_id());
					ret_prd_in.setMtrl_pallet_id(item.getPpbox());
					ret_prd_in.setPrd_tl_qty(item.getDiffCnt());
					ret_prd_in.setPrd_act_qty(item.getDiffCnt());
					ret_prd_in.setPrd_proc_qty(0);
					ret_prd_in.setRcv_usr(inTrx.getEvt_user());
					ret_prd_in.setRcv_timestamp(gEvtTimestamp);
					ret_prd_in.setEvt_cate(EVT_MTRL_IN);
					ret_prd_in.setEvt_usr(inTrx.getEvt_user());
					ret_prd_in.setEvt_timestamp(gEvtTimestamp);
					ret_prd_in.setBox_std_qty(item.getBox_std_qty());
					retPrdInDao.save(ret_prd_in);
				}
				
				// Add wo
				rtnBeen = syncWoInfo(inTrx.getAction_flg(), item.getWo_id(),
						item.getMtrl_type(), item.getDiffCnt());
				if (_NORMAL != rtnBeen.getlRc()) {
					return rtnBeen.getlRc();
				}
				
				
				Ret_wo retWo = retWODao.getWithLock(item.getWo_id(), LockMode.UPGRADE);
				String cusId = retWo.getCus_id_fk();
				boolean isXMTMProc = bisDataDao.checkEdiCusProc("XMTM",cusId);
				if(isXMTMProc){
					String boxId = item.getBox_id();
					Ret_tm_cus_prd_in tmBox = retTmCusPrdInDao.get(boxId);
						if(tmBox!=null){
							String tmCusMtrlProdId = tmBox.getProductspecname().substring(0,9);
							String woMtrlProdId = retWo.getMtrl_prod_id_fk().substring(0,9);
							
							if(!woMtrlProdId.equals(tmCusMtrlProdId)){
								gszMsgBuf = "内部订单[" + item.getWo_id() 
										+ "]与来料箱[" 
										+ item.getBox_id() + "]的来料型号不匹配，无法收料!";
								logger.error(woMtrlProdId + " vs " + tmCusMtrlProdId);
								return E_XPWHSOPE_MTEL_PROD_ID_MISMATCH_ERROR;
							}
							tmBox.setAct_flg(_YES);
							retTmCusPrdInDao.update(tmBox);
						}
				}
				
				//check rl_prd_qty
//				Ret_wo nowWo = retWODao.get(item.getWo_id());
//				int rlcnt = retPrdInfoDao.getrlPrdCnt(item.getWo_id());
//				if(nowWo.getRl_prd_qty()!=rlcnt){
//					nowWo.setRl_prd_qty(rlcnt);
//					retWODao.update(nowWo);
//				}
				xpaplywoO = (XpaplywoO) rtnBeen.getObj();

				XpwhsopeOA oa = new XpwhsopeOA();
				oa.setVdr_id(ret_prd_in.getId().getCus_id());
				oa.setBox_id(ret_prd_in.getId().getMtrl_box_id());
				oa.setMtrl_type(ret_prd_in.getMtrl_prod_id_fk());
				oa.setDest_shop(ret_prd_in.getStb_shop());
				oa.setWo_id(ret_prd_in.getWo_id_fk());
				oa.setCount(ret_prd_in.getPrd_tl_qty().toString());
				oa.setWeight(ret_prd_in.getBox_weight().toString());
				oa.setRcv_user(ret_prd_in.getRcv_usr());
				oa.setRcv_timestamp(ret_prd_in.getRcv_timestamp().toString());
				oa.setEvt_user(ret_prd_in.getEvt_usr());
				oa.setEvt_timestamp(ret_prd_in.getEvt_timestamp().toString());
				oa.setPpbox_stat(ret_prd_in.getPpbox_stat());
				oa.setWo_pln_cnt(String.valueOf(xpaplywoO.getOary().get(0).getPln_prd_qty()));
				oa.setBox_std_qty(ret_prd_in.getBox_std_qty());
	//			oa.setWo_rl_prd_qty(nowWo.getRl_prd_qty());
				oaList.add(oa);
			}
			outTrx.setBox_cnt(inTrx.getIary().size());
			outTrx.setOary(oaList);
		}
		return lRc;
	}

	private long createRetBoxByMtrlBoxId() {
		long lRc = _NORMAL;
		double dZero = 0;
		if (inTrx.getBox_cnt() > 0) {
			for (XpwhsopeIA item : inTrx.getIary()) {
				Ret_box ret_box = retBoxDao.get(item.getBox_id());
				if (ret_box == null) {
					ret_box = new Ret_box();
					ret_box.setBox_id(item.getBox_id());
					ret_box.setBox_stat(PROC_EMPTY);
					ret_box.setReal_emp(_YES);
					ret_box.setValid_flg(_YES);
					ret_box.setBox_use_cnt(0);
					ret_box.setStd_qty(item.getBox_std_qty());
					ret_box.setPrd_qty(0);
					ret_box.setBox_cate(JBIC_BOX_SET_CODE);
					ret_box.setBox_size(item.getBox_std_qty().toString() + "PC");
					ret_box.setBox_set_code(JBIC_BOX_SET_CODE);
					ret_box.setBox_rgst_timestamp(gEvtTimestamp);
					ret_box.setBox_weight(dZero);
					ret_box.setMdl_weight(dZero);
					ret_box.setMeg_mdl_weight(dZero);
					ret_box.setBnk_flg(BANK_OUT);
					ret_box.setEvt_cate("BULD");
					ret_box.setEvt_usr(inTrx.getEvt_user());
					ret_box.setEvt_timestamp(gEvtTimestamp);
					ret_box.setEvt_time_d(Util.getDoubleTime());
					ret_box.setPrd_admin_flg("NNNNNNNNNNNNNNNNNNNN");
					retBoxDao.save(ret_box);
				} else {
					ret_box.setStd_qty(item.getBox_std_qty());
					ret_box.setBox_size(item.getBox_std_qty().toString());

					retBoxDao.update(ret_box);
				}
			}
		}
		return lRc;
	}

	/**
	 * Delete one mtrl panel box
	 * 
	 * @return
	 */
	private long deletePanelMtrlRecord() {
		long lRc = _NORMAL;
		SimpleRtnBeen rtnBeen = new SimpleRtnBeen(_NORMAL);
		XpaplywoO xpaplywoO = new XpaplywoO();
		List<XpwhsopeOA> oaList = new ArrayList<XpwhsopeOA>();

		if (inTrx.getBox_cnt() > 0) {
			for (XpwhsopeIA item : inTrx.getIary()) {
				Ret_prd_in ret_prd_in = new Ret_prd_in();
				Ret_prd_inId ret_prd_inId = new Ret_prd_inId();
				ret_prd_inId.setCus_id(item.getVdr_id());
				ret_prd_inId.setMtrl_box_id(item.getBox_id());

				ret_prd_in = retPrdInDao.get(ret_prd_inId);
				if (null == ret_prd_in) {
					gszMsgBuf = "箱号为[" + item.getBox_id() + "],客户代码为["
							+ item.getVdr_id() + "]的箱子不存在!";
					return E_RET_PRD_IN + E_DELETE_NOT_FOUND;
				}

				if (!PROC_WAIT.equals(ret_prd_in.getPpbox_stat())) {
					gszMsgBuf = "箱子 [" + item.getBox_id() + "] 状态不正确 ["
							+ ret_prd_in.getPpbox_stat()
							+ "]，不允许删除，只允许删除未发料的箱子!";
					return E_XPWHSOPE_INVALID_BOX_STAT;
				}
				ret_prd_in.setEvt_cate(EVT_MTRL_IN_CANCEL);
				retPrdInDao.deleteByKey(ret_prd_inId);

				/**
				 * 客户来料箱，更新ACT_FLG为N
				 */
				Ret_cus_prd_in cusPrdIn = retCusPrdInDao.get(item.getBox_id());
				if(cusPrdIn != null){
					cusPrdIn.setAct_flg(_NO);
					retCusPrdInDao.save(cusPrdIn);
				}
				// update wo
				rtnBeen = syncWoInfo(inTrx.getAction_flg(), item.getWo_id(),
						item.getMtrl_type(), item.getDiffCnt());
				if (_NORMAL != rtnBeen.getlRc()) {
					return rtnBeen.getlRc();
				}
				xpaplywoO = (XpaplywoO) rtnBeen.getObj();

			}

			if (null != xpaplywoO) {
				XpwhsopeOA oa = new XpwhsopeOA();
				oa.setWo_pln_cnt(String.valueOf(xpaplywoO.getOary().get(0)
						.getPln_prd_qty()));
				oaList.add(oa);
			}
			outTrx.setBox_cnt(inTrx.getIary().size());
			outTrx.setOary(oaList);
		}

		return lRc;
	}

	/**
	 * Update one mtrl panel box
	 * 
	 * @return
	 */
	private long updatePanelMtrlRecord() {
		long lRc = _NORMAL;
		SimpleRtnBeen rtnBeen = new SimpleRtnBeen(_NORMAL);
		XpaplywoO xpaplywoO = new XpaplywoO();
		List<XpwhsopeOA> oaList = new ArrayList<XpwhsopeOA>();

		String vdrID = inTrx.getIary().get(0).getVdr_id();
		String boxID = inTrx.getIary().get(0).getBox_id();

		Ret_prd_in ret_prd_in = new Ret_prd_in();
		Ret_prd_inId ret_prd_inId = new Ret_prd_inId();

		ret_prd_inId.setMtrl_box_id(boxID);
		ret_prd_inId.setCus_id(vdrID);
		ret_prd_in = retPrdInDao.get(ret_prd_inId);
		if (null == ret_prd_in) {
			gszMsgBuf = "箱号为 [" + boxID + "], 客户代码为[" + vdrID
					+ "]的箱子不存在，不允许更新!";
			return E_RET_PRD_IN + E_UPDATE_NOT_FOUND;
		}

		if (!PROC_WAIT.equals(ret_prd_in.getPpbox_stat())) {
			gszMsgBuf = "箱子 [" + boxID + "] 状态不正确 ["
					+ ret_prd_in.getPpbox_stat() + "]，不允许修改，只允许修改未发料的箱子!";
			return E_XPWHSOPE_INVALID_BOX_STAT;
		}
		/**
		 * change for mdc 当prd_tl_qty和box_std_qty变更时  先删除，再新增。以做区分
		 * 删除时，EVT_CATE定义为MTIC
		 * 新增时，EVT_CATE定义为MTIN
		 */
		ret_prd_in.setEvt_cate(EVT_MTRL_IN_CANCEL);
		retPrdInDao.deleteByKey(ret_prd_inId);
		
		ret_prd_in.setMtrl_prod_id_fk(inTrx.getIary().get(0).getMtrl_type());
		ret_prd_in.setStb_shop(inTrx.getIary().get(0).getDest_shop());
		ret_prd_in.setBox_std_qty(inTrx.getIary().get(0).getBox_std_qty());
		ret_prd_in.setPrd_tl_qty(ret_prd_in.getPrd_tl_qty()
				+ inTrx.getIary().get(0).getDiffCnt());
		ret_prd_in.setPrd_act_qty(ret_prd_in.getPrd_act_qty()
				+ inTrx.getIary().get(0).getDiffCnt());
		ret_prd_in.setBox_weight(Double.valueOf(inTrx.getIary().get(0)
				.getWeight()));

		ret_prd_in.setEvt_usr(inTrx.getEvt_user());
		ret_prd_in.setEvt_timestamp(gEvtTimestamp);
		ret_prd_in.setRcv_timestamp(gEvtTimestamp);
		ret_prd_in.setEvt_cate(EVT_MTRL_IN);
		retPrdInDao.save(ret_prd_in);

		// Update wo
		if (0 != inTrx.getIary().get(0).getDiffCnt()) {
			rtnBeen = syncWoInfo(inTrx.getAction_flg(),
					ret_prd_in.getWo_id_fk(), ret_prd_in.getMtrl_prod_id_fk(),
					inTrx.getIary().get(0).getDiffCnt());
			if (_NORMAL != rtnBeen.getlRc()) {
				return rtnBeen.getlRc();
			}
			xpaplywoO = (XpaplywoO) rtnBeen.getObj();
			XpwhsopeOA oa = new XpwhsopeOA();
			oa.setWo_pln_cnt(String.valueOf(xpaplywoO.getOary().get(0)
					.getPln_prd_qty()));
			oaList.add(oa);
		}

		outTrx.setBox_cnt(inTrx.getIary().size());
		outTrx.setOary(oaList);

		return lRc;
	}

	/**
	 * Query mtrl box info by input condition
	 * 
	 * @return
	 */
	private long queryPanelMaterial() {
		long lRc = _NORMAL;
		Ret_prd_in ret_prd_in = new Ret_prd_in();
		Ret_prd_inId ret_prd_inId = new Ret_prd_inId();
		List<Ret_prd_in> ret_prd_inList = new ArrayList<Ret_prd_in>();

		String hqlQuery = "FROM Ret_prd_in where 1=1 ";
		if (!Util.isSpaceCheck(inTrx.getBox_stats())) {
			hqlQuery += " AND ppbox_stat IN ( " + inTrx.getBox_stats() + " )";
		} else if (!Util.isSpaceCheck(inTrx.getBox_stat())) {
			hqlQuery += " AND ppbox_stat = '" + inTrx.getBox_stat() + "' ";
		}

		if (null != inTrx.getIary()) {
			if (!Util.isSpaceCheck(inTrx.getIary().get(0).getVdr_id())
					&& !Util.isSpaceCheck(inTrx.getIary().get(0).getBox_id())) {
				ret_prd_inId.setCus_id(inTrx.getIary().get(0).getVdr_id());
				ret_prd_inId.setMtrl_box_id(inTrx.getIary().get(0).getBox_id());
				ret_prd_in = retPrdInDao.get(ret_prd_inId);
				if (null != ret_prd_in) {
					ret_prd_inList.add(ret_prd_in);
				}
			} else {
				if (!Util.isSpaceCheck(inTrx.getIary().get(0).getVdr_id())) {
					hqlQuery += " AND id.cus_id = '"
							+ inTrx.getIary().get(0).getVdr_id() + "' ";
				}
				if (!Util.isSpaceCheck(inTrx.getIary().get(0).getMtrl_type())) {
					hqlQuery += " AND mtrl_prod_id_fk = '"
							+ inTrx.getIary().get(0).getMtrl_type() + "' ";
				}
				if (!Util.isSpaceCheck(inTrx.getIary().get(0).getBox_id())) {
					hqlQuery += " AND id.mtrl_box_id = '"
							+ inTrx.getIary().get(0).getBox_id() + "' ";
				}
				if (!Util.isSpaceCheck(inTrx.getIary().get(0).getDest_shop())) {
					hqlQuery += " AND stb_shop in("
							+ inTrx.getIary().get(0).getDest_shop() + ")";
				}
				if (!Util.isSpaceCheck(inTrx.getIary().get(0).getWo_id())) {
					hqlQuery += " AND wo_id_fk = '"
							+ inTrx.getIary().get(0).getWo_id() + "' ";
				} else if (!Util.isSpaceCheck(inTrx.getIary().get(0)
						.getWo_ids())) {
					hqlQuery += " AND wo_id_fk IN ( "
							+ inTrx.getIary().get(0).getWo_ids() + " )";
				}
				hqlQuery += "ORDER BY RCV_TIMESTAMP";
				ret_prd_inList = retPrdInDao.find(hqlQuery);
			}
		}

		if (!ret_prd_inList.isEmpty()) {
			outTrx.setBox_cnt(ret_prd_inList.size());
			List<XpwhsopeOA> oaList = new ArrayList<XpwhsopeOA>();
			for (Ret_prd_in item : ret_prd_inList) {
				XpwhsopeOA oa = new XpwhsopeOA();
				oa.setVdr_id(item.getId().getCus_id());
				oa.setBox_id(item.getId().getMtrl_box_id());
				oa.setMtrl_type(item.getMtrl_prod_id_fk());
				oa.setDest_shop(item.getStb_shop());
				oa.setDest_shop_dsc(item.getStb_shop());
				oa.setWo_id(item.getWo_id_fk());
				oa.setCount(item.getPrd_tl_qty().toString());
				oa.setWeight(item.getBox_weight().toString());
				oa.setRcv_user(item.getRcv_usr());// 入库人员
				oa.setRcv_timestamp(item.getRcv_timestamp().toString());// 入库时间
				oa.setEvt_user(item.getEvt_usr());// 发料人员
				oa.setEvt_timestamp(item.getEvt_timestamp().toString());// 发料和收料时间
				oa.setRelate_user(item.getRelate_usr());// 收料人员
				oa.setPpbox_stat(item.getPpbox_stat());
				oa.setBox_std_qty(item.getBox_std_qty());
				oa.setCus_id(item.getId().getCus_id());
				oaList.add(oa);
			}
			outTrx.setOary(oaList);
		} else {
			outTrx.setBox_cnt(0);
		}

		return lRc;
	}

	/**
	 * Change Ret_prd_in Stat
	 * @return
	 */
	private long changeMtrlStat(){
		SimpleRtnBeen rtnBeen = new SimpleRtnBeen(_NORMAL);

		if (inTrx.getWo_id() == null ){
			gszMsgBuf = "退料时候工单不能为空！";
		    return E_XPWHSOPE_INVALID_INPUT;
		}
		
		
		List<XpwhsopeIA> iary = inTrx.getIary();
		for (XpwhsopeIA xpwhsopeIA:iary){
			
			//Check Input Data
			if (Util.isSpaceCheck(xpwhsopeIA.getBox_id())) {
				gszMsgBuf = "来料箱号不能为空！";
			    return E_XPWHSOPE_INVALID_INPUT;
			}
			if (Util.isSpaceCheck(xpwhsopeIA.getCus_id())) {
				gszMsgBuf = "客户代码不能为空！请选择客户代码后重新查询！";
			    return E_XPWHSOPE_INVALID_INPUT;
			}
			
			//联合之间set值
			Ret_prd_inId id = new Ret_prd_inId();
			id.setCus_id(xpwhsopeIA.getCus_id());
			id.setMtrl_box_id(xpwhsopeIA.getBox_id());
			
			//主键查询
			Ret_prd_in prd_in = new Ret_prd_in();
			prd_in = retPrdInDao.get(id);
			
			//箱号不存在，报错
			if(null == prd_in){
				gszMsgBuf = "来料箱号不存在！";
			    return E_XPWHSOPE_MTRL_BOX_ALREADY_EXIST;
			}
			
			if (prd_in.getPrd_proc_qty() != 0) {
				gszMsgBuf = "来料箱号["+ prd_in.getId().getMtrl_box_id() +"]已提配，不能取消发料！";
			    return E_XPWHSOPE_RELEASED_BOX_BACK_ERROR;
			}
			
			//赋值
			prd_in.setPpbox_stat("WAIT");
			prd_in.setEvt_cate(EVT_MTRL_RELEASE_CANCEL);
			
			//udpate
			retPrdInDao.update(prd_in);
			
		}

			
		return _NORMAL;
	}
	
	/**
	 * List all mtrl box info
	 * 
	 * @return
	 */
	private long listPanelMaterial() {
		long lRc = _NORMAL;

		List<Ret_prd_in> ret_prd_inList = new ArrayList<Ret_prd_in>();
		ret_prd_inList = retPrdInDao.loadAll();
		outTrx.setBox_cnt(ret_prd_inList.size());
		if (ret_prd_inList.size() > 0) {
			List<XpwhsopeOA> oaList = new ArrayList<XpwhsopeOA>();
			for (Ret_prd_in item : ret_prd_inList) {
				XpwhsopeOA oa = new XpwhsopeOA();
				oa.setBox_id(item.getId().getMtrl_box_id());
				oa.setGrade(item.getMtrl_gd());
				oa.setPallet_id(item.getMtrl_pallet_id());
				oa.setBatch_no(item.getMtrl_lot_id());
				oa.setCount(item.getPrd_tl_qty().toString());
				oa.setRcv_user(item.getRcv_usr());
				oa.setRcv_timestamp(item.getRcv_timestamp().toString());
				oa.setEvt_user(item.getEvt_usr());
				oa.setEvt_timestamp(item.getEvt_timestamp().toString());
				oa.setPpbox_stat(item.getPpbox_stat());
				oaList.add(oa);
			}
			outTrx.setOary(oaList);
		}

		return lRc;
	}

	/**
	 * Use mtrl panel Update status
	 * 
	 * @return
	 */
	private long mtrlPanelUseChg(String chgType) {
		SimpleRtnBeen rtnBeen = new SimpleRtnBeen(_NORMAL);
		long lRc = _NORMAL;
		String chgStat = "";
		String relateUsr = "";
		String hqlQuery = "";

		if (inTrx.getBox_cnt() > 0) {
			for (XpwhsopeIA iary : inTrx.getIary()) {
				Ret_prd_in ret_prd_in = new Ret_prd_in();
				hqlQuery = "FROM Ret_prd_in where wo_id_fk = '"
						+ iary.getWo_id() + "' AND " + " id.mtrl_box_id = '"
						+ iary.getBox_id() + "' ";
				ret_prd_in = (Ret_prd_in) retPrdInDao.comTblRead(hqlQuery);
				if (null != ret_prd_in) {
					// Use || Un Use 发料
					if (USE_CHG_U == chgType) {
						chgStat = PROC_WFRL;
						relateUsr = inTrx.getRelate_usr();
						if (!PROC_WAIT.equals(ret_prd_in.getPpbox_stat())) {// Check
																			// must
																			// be
																			// WAIT
							gszMsgBuf = "箱号[" + iary.getBox_id() + "]已经发料!";
							return E_XPWHSOPE_BOX_ALREADY_RELEASED;
						}
					} else if (USE_CHG_R == chgType) {
						chgStat = PROC_WAIT;
						relateUsr = _SPACE0;
						if (!PROC_WFRL.equals(ret_prd_in.getPpbox_stat())) {
							gszMsgBuf = "箱号[" + iary.getBox_id() + "]未发料!";
							return E_XPWHSOPE_BOX_NOT_RELEASED;
						}
					} else {
						gszMsgBuf = "Invalide type FOR USE CHANGE: [" + chgType
								+ "]";
						return E_XPWHSOPE_INVALID_USE_CHANGE_TYPE;
					}

					ret_prd_in.setPpbox_stat(chgStat);
					ret_prd_in.setRelate_usr(relateUsr);
					ret_prd_in.setEvt_cate(EVT_MTRL_RELEASE_TO_PROD);
					ret_prd_in.setEvt_usr(inTrx.getEvt_user());
					ret_prd_in.setEvt_timestamp(gEvtTimestamp);

					retPrdInDao.update(ret_prd_in);
				} else {
					gszMsgBuf = "内部订单[" + iary.getWo_id() + "]未找到箱号为["
							+ iary.getBox_id() + "]的箱子";
					return E_RET_PRD_IN + E_READ_NOT_FOUND;
				}
			}
		}

		return lRc;
	}

	/**
	 * 来料时同步工单信息：新建、修改数量（A/D）
	 * 
	 * @param wo_id
	 * @param mtrl_type
	 * @param diffCnt
	 * @return
	 */
	private SimpleRtnBeen syncWoInfo(String act_flg, String wo_id,
			String mtrl_type, Integer diffCnt) {
		SimpleRtnBeen rtnBeen = new SimpleRtnBeen(_NORMAL);
		MqOpe mqOpe_XPMOVEOUT = new MqOpe();

		XpaplywoI xpaplywoI = new XpaplywoI();
		XpaplywoIA xpaplywoIA = new XpaplywoIA();
		List<XpaplywoIA> xpaplywoIAList = new ArrayList<XpaplywoIA>();

		XpaplywoO xpaplywoO = new XpaplywoO();
		String xpaplywoOString = null;

		
		xpaplywoI.setTrx_id(T_XPAPLYWO);
		xpaplywoI.setType_id(TRX_IN);
		xpaplywoI.setTbl_cnt(1);
		xpaplywoI.setAction_flg("N");
		xpaplywoI.setAct_flg(act_flg);
		xpaplywoIA.setMtrl_prod_id_fk(mtrl_type);
		xpaplywoIA.setWo_id(wo_id);
		xpaplywoIA.setPln_prd_qty(diffCnt.toString());
		xpaplywoIA.setEvt_user(inTrx.getEvt_user());
		xpaplywoIAList.add(xpaplywoIA);
		xpaplywoI.setIary(xpaplywoIAList);

		xpaplywoOString = xpaplywoService.subMainProc(mqOpe_XPMOVEOUT
				.obj2Str(xpaplywoI));
		xpaplywoO = (XpaplywoO) mqOpe_XPMOVEOUT.inStr2Obj(xpaplywoOString,
				xpaplywoO);
		if (!xpaplywoO.getRtn_code().equals(RETURN_CODE_OK)) {
			gszMsgBuf = xpaplywoO.getRtn_mesg();
			return new SimpleRtnBeen(E_XPWHSOPE_ADD_UPDATE_WOINFO_FAILED);
		}

		return new SimpleRtnBeen(xpaplywoO);

	}

}
